package com.plugin.appinit

import com.google.gson.Gson
import javassist.ClassPool
import javassist.CtClass
import javassist.CtField
import javassist.Modifier
import org.gradle.api.Project

/**
 * @author GYL
 * @dateTime 2020/5/19-10:17
 * @description
 */
class AppInitialManagerTransform {
  CtClass appInitManagerCtClass
  ClassPool classPool
  Project mProject
  ArrayList<AppInitItem> pathList
  String contentField = "INIT_LIST"

  AppInitialManagerTransform(Project project, CtClass ctClass, ArrayList<AppInitItem> pathList, ClassPool classPool) {
    this.appInitManagerCtClass = ctClass
    this.classPool = classPool
    this.mProject = project
    this.pathList = pathList
  }


  void handleActivitySaveState() {
    mProject.logger.error(">>  AppInitialManagerTransform ${appInitManagerCtClass.name} ")
    String content = ""
    try {
      content = new Gson().toJson(pathList)
    } catch (Exception e) {
      e.printStackTrace()
    }
    mProject.logger.error(">>  AppInitialManagerTransform initList : ${content}")
    generateEnabledField(appInitManagerCtClass, content)
    mProject.logger.error(">>  AppInitialManagerTransform fields  : ${appInitManagerCtClass.declaredFields}")
  }


  void generateEnabledField(CtClass ctClass, String path) {
    CtField pathCtField = ctClass.declaredFields.find {
      it.name == contentField && it.getType().name == "java.lang.String"
    }
    if (pathCtField != null) {
      ctClass.removeField(pathCtField)
    }
    pathCtField = new CtField(classPool.get("java.lang.String"), contentField, ctClass)
    pathCtField.setModifiers(Modifier.PRIVATE | Modifier.STATIC )
    ctClass.addField(pathCtField, CtField.Initializer.constant(path))
  }


}
